| Conditions | 6 |
| Total Lines | 62 |
| Code Lines | 51 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | import * as crypto from 'crypto'; |
||
| 77 | |||
| 78 | registerViewEngine(app: NestExpressApplication, assetsRoot: string): void { |
||
| 79 | const express = app.getHttpAdapter().getInstance(); |
||
| 80 | |||
| 81 | this.env = this.createEnv(express.get('views')); |
||
| 82 | |||
| 83 | app.use((req: Request, res: Response, next: NextFunction): void => { |
||
| 84 | const ctx = (res.locals.njkCtx = res.locals.njkCtx ?? {}); |
||
| 85 | |||
| 86 | ctx['req'] = req; |
||
| 87 | |||
| 88 | ctx['path'] = (name: string, params: object = {}) => { |
||
| 89 | try { |
||
| 90 | return this.resolver.resolve(name, params); |
||
| 91 | } catch (err) { |
||
| 92 | console.error( |
||
| 93 | `Failed to resolve path ${name} with params ${JSON.stringify( |
||
| 94 | params |
||
| 95 | )}: ${err}` |
||
| 96 | ); |
||
| 97 | return '#'; |
||
| 98 | } |
||
| 99 | }; |
||
| 100 | |||
| 101 | ctx['url'] = (name: string, params: object = {}) => { |
||
| 102 | try { |
||
| 103 | const path = this.resolver.resolve(name, params); |
||
| 104 | const proto = req.protocol; |
||
| 105 | const origin = req.get('Host'); |
||
| 106 | const baseUrl = `${proto}://${origin}`; |
||
| 107 | const url = new URL(path, baseUrl); |
||
| 108 | return url.toString(); |
||
| 109 | } catch { |
||
| 110 | return '#'; |
||
| 111 | } |
||
| 112 | }; |
||
| 113 | |||
| 114 | ctx['view_name'] = this.resolver.getName(req.url); |
||
| 115 | |||
| 116 | ctx['asset'] = (path: string) => { |
||
| 117 | return `${assetsRoot === '/' ? '' : assetsRoot}/${path}`; |
||
| 118 | }; |
||
| 119 | |||
| 120 | ctx['now'] = new Date(); |
||
| 121 | |||
| 122 | ctx['theme'] = req.cookies.theme; |
||
| 123 | |||
| 124 | next(); |
||
| 125 | }); |
||
| 126 | |||
| 127 | app.engine( |
||
| 128 | 'njk', |
||
| 129 | ( |
||
| 130 | name: string, |
||
| 131 | ctx: Record<string, any>, |
||
| 132 | cb: TemplateCallback<string> |
||
| 133 | ) => { |
||
| 134 | this.env.render(name, { ...ctx, ...ctx._locals.njkCtx }, cb); |
||
| 135 | } |
||
| 136 | ); |
||
| 137 | |||
| 138 | app.setViewEngine('njk'); |
||
| 139 | } |
||
| 149 |